#ifndef CONNECTIONGUARD_H
#define CONNECTIONGUARD_H

#include <rtos/thread.h>
#include <functional>
#include <clock.h>
#include <signal_os.h>
#include <units.h>
using namespace units::literals;

namespace os {
class ConnectionGuard {
   public:
    static ConnectionGuard& instance() {
        static ConnectionGuard i;
        return i;
    }
    static void addGuard(std::function<void()> const& _) { guard_().connect(_); }

    ConnectionGuard(ConnectionGuard const&) = delete;
    ConnectionGuard& operator=(ConnectionGuard const&) = delete;

    uint32_t stack_[512]{};  // 线程栈
    StaticTask_t tcb_{};     // 线程控制块

   private:
    Thread _;
    static Signal<>& guard_() {
        static Signal<> i;  // 静态信号对象声明
        return i;
    }
    ConnectionGuard()
        : _(Thread{[&](void*) {
                       for (;;) {
                           guard_().emit();
                           sleep(200_ms);
                       }
                   },
                   "ConnectionGuard", 512, nullptr, 5, stack_, &tcb_}) {}
    ~ConnectionGuard() = default;
};
}  // namespace os

#define USE_CONNECTION_GUARD os::ConnectionGuard& __connection_guard__ = os::ConnectionGuard::instance();

#endif  // CONNECTIONGUARD_H